package com.jvm;

import java.util.concurrent.Semaphore;

/**
 * 项目名称: java_algorithm
 * @ClassName SemaphoreTest
 * @Description
 * @Author huipanxing huipanxing@chinasofti.com   @Date 2021/10/14 10:25
 */
public class SemaphoreTest {

    /**
     * Semaphore 信号量的构造参数 为acquire方法可以拿到的许可证
     * release 方法是释放许可证 许可证的数量少于初始化的数量就可以继续抢到
     * 否则就阻塞
     *
     */
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("抢到了" + finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
//                    semaphore.release();
//                    System.out.println("释放"+ finalI);
                }
            }).start();
        }

        for (int i = 1; i <= 6; i++) {
            int finalI = i;
            Thread.sleep(2000);
            new Thread(() -> {
                semaphore.release(1);
                System.out.println("释放" + finalI);
            }).start();
        }
    }
}
